/**
 * 引导对话界面组件
 * AI引导用户逐步明确创作需求
 */

import React, { useState, useEffect } from 'react'
import {
  Card,
  Typography,
  Input,
  Button,
  Radio,
  Space,
  Steps,
  InputNumber,
  Tooltip,
  Divider,
  Alert
} from 'antd'
import {
  MessageOutlined,
  ArrowLeftOutlined,
  ArrowRightOutlined,
  CheckCircleOutlined,
  LoadingOutlined,
  QuestionCircleOutlined
} from '@ant-design/icons'
import {
  DialogStep,
  SparkDialogState,
  DialogStepType,
  WORD_COUNT_PRESETS,
  SECTION_COUNT_RULES,
  SectionCountRule
} from '../../../types/spark'

const { TextArea } = Input
const { Title, Paragraph, Text } = Typography
const { Step } = Steps

export interface DialogInterfaceProps {
  dialogStep: DialogStep
  dialogState: SparkDialogState
  onUserResponse: (response: string) => void
  onComplete?: () => void
  isLoading?: boolean
}

const DialogInterface: React.FC<DialogInterfaceProps> = ({
  dialogStep,
  dialogState,
  onUserResponse,
  isLoading = false
}) => {
  const [userInput, setUserInput] = useState('')
  const [selectedOption, setSelectedOption] = useState<string>('')

  // AUDIENCE_STYLE步骤的新状态
  const [selectedAudience, setSelectedAudience] = useState('')
  const [totalWords, setTotalWords] = useState(800)
  const [sectionCount, setSectionCount] = useState(4)

  // 获取段落数规则
  const getSectionRule = (words: number): SectionCountRule => {
    return SECTION_COUNT_RULES.find(
      rule => words >= rule.minWords && words <= rule.maxWords
    ) || SECTION_COUNT_RULES[SECTION_COUNT_RULES.length - 1]
  }

  const currentRule = getSectionRule(totalWords)

  // 字数变化时自动调整段落数
  useEffect(() => {
    const rule = getSectionRule(totalWords)
    if (sectionCount < rule.minSections || sectionCount > rule.maxSections) {
      setSectionCount(rule.recommendedSections)
    }
  }, [totalWords])

  // 处理预设字数按钮
  const handlePresetClick = (value: number) => {
    setTotalWords(value)
  }

  // 处理自定义字数输入
  const handleWordsChange = (value: number | null) => {
    if (value && value >= 100 && value <= 5000) {
      setTotalWords(value)
    }
  }

  // 处理段落数变化
  const handleSectionCountChange = (value: number | null) => {
    if (value && value >= currentRule.minSections && value <= currentRule.maxSections) {
      setSectionCount(value)
    }
  }

  // 获取合理性提示
  const getValidationMessage = (): { type: 'success' | 'warning', text: string } => {
    const avgPerSection = Math.round(totalWords / sectionCount)

    if (avgPerSection < 80) {
      return {
        type: 'warning',
        text: `每段平均不足80字，内容可能过于简略，建议减少段落数`
      }
    } else if (avgPerSection > 400) {
      return {
        type: 'warning',
        text: `每段平均超过400字，读者可能感到疲劳，建议增加段落数`
      }
    } else {
      return {
        type: 'success',
        text: `段落配置合理：${totalWords}字分${sectionCount}段，平均每段${avgPerSection}字`
      }
    }
  }

  // 处理回答提交
  const handleSubmit = () => {
    let response: string

    // AUDIENCE_STYLE步骤使用特殊格式
    if (dialogStep.type === DialogStepType.AUDIENCE_STYLE) {
      response = `${selectedAudience}，文章字数${totalWords}字，分${sectionCount}段`
    } else if (dialogStep.options) {
      response = selectedOption
    } else {
      response = userInput
    }

    if (response.trim()) {
      onUserResponse(response)
      setUserInput('')
      setSelectedOption('')
    }
  }

  // 处理键盘快捷键
  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) {
      handleSubmit()
    }
  }

  // 获取步骤标题
  const getStepTitle = (stepType: DialogStepType): string => {
    return 'AI的帮助消息'
  }

  // 渲染进度步骤
  const renderSteps = () => {
    const steps = [
      { title: '明确主题', type: DialogStepType.TOPIC_CLARIFICATION },
      { title: '确定风格', type: DialogStepType.AUDIENCE_STYLE },
      { title: '规划结构', type: DialogStepType.STRUCTURE_PLANNING },
      { title: '生成大纲', type: DialogStepType.OUTLINE_GENERATION }
    ]

    // 判断是否在最后一步且正在加载（即正在生成大纲）
    const isGeneratingOutline = dialogState.currentStep === steps.length - 1 && isLoading

    return (
      <Steps
        current={isGeneratingOutline ? steps.length - 1 : dialogState.currentStep}
        size="small"
        style={{ marginBottom: 24 }}
      >
        {steps.map((step, index) => {
          const isLastStep = index === steps.length - 1
          return (
            <Step
              key={step.type}
              title={step.title}
              status={
                index < dialogState.currentStep ? 'finish' :
                index === dialogState.currentStep ? (isLoading && isLastStep ? 'process' : 'process') : 'wait'
              }
              icon={
                index < dialogState.currentStep ? <CheckCircleOutlined /> :
                index === dialogState.currentStep && isLoading && isLastStep ? <LoadingOutlined /> : undefined
              }
            />
          )
        })}
      </Steps>
    )
  }

  // 渲染已回答的问题回顾
  const renderPreviousAnswers = () => {
    const answers = []
    const { responses } = dialogState

    if (responses.topic) {
      answers.push({ label: '创作主题', value: responses.topic })
    }
    if (responses.audience) {
      answers.push({ label: '目标受众', value: responses.audience })
    }
    if (responses.tone) {
      answers.push({ label: '写作风格', value: responses.tone })
    }
    if (responses.structure) {
      answers.push({ label: '文章结构', value: responses.structure })
    }

    if (answers.length === 0) return null

    return (
      <Card
        size="small"
        style={{ marginBottom: 12, background: '#f8f9fa' }}
        bodyStyle={{ padding: 12 }}
      >
        <div style={{ fontSize: 12, color: '#666', marginBottom: 6 }}>
          已确认信息：
        </div>
        {answers.map((answer, index) => (
          <div key={index} style={{ marginBottom: 4, fontSize: 12 }}>
            <Text strong style={{ color: '#333' }}>
              {answer.label}：
            </Text>
            <Text style={{ color: '#666', marginLeft: 4 }}>
              {answer.value}
            </Text>
          </div>
        ))}
      </Card>
    )
  }

  // 渲染问题内容
  const renderQuestion = () => (
    <Card
      className="dialog-question"
      size="small"
      style={{ marginBottom: 12 }}
      bodyStyle={{ padding: 16 }}
    >
      <div style={{ display: 'flex', alignItems: 'flex-start', gap: 12 }}>
        <MessageOutlined style={{ color: '#1890ff', fontSize: 16, marginTop: 2 }} />
        <div style={{ flex: 1 }}>
          <Title level={5} style={{ margin: '0 0 8px 0', color: '#1890ff', fontSize: 14, fontWeight: 600 }}>
            {getStepTitle(dialogStep.type)}
          </Title>
          <Paragraph style={{ margin: 0, color: '#333', lineHeight: 1.5, fontSize: 14 }}>
            {dialogStep.question}
          </Paragraph>
          {dialogStep.helpText && (
            <div style={{ marginTop: 8, fontSize: 12, color: '#666', lineHeight: 1.4 }}>
              💡 {dialogStep.helpText}
            </div>
          )}
        </div>
      </div>
    </Card>
  )

  // 渲染回答区域
  const renderResponseArea = () => {
    // AUDIENCE_STYLE步骤使用新的UI
    if (dialogStep.type === DialogStepType.AUDIENCE_STYLE) {
      const validation = getValidationMessage()

      return (
        <>
          {/* 受众选择 */}
          <Card title="1. 请选择目标受众" size="small" style={{ marginBottom: 12 }}>
            <Radio.Group
              value={selectedAudience}
              onChange={(e) => setSelectedAudience(e.target.value)}
            >
              <Space direction="vertical">
                <Radio value="专业人士">专业人士（正式、专业术语）</Radio>
                <Radio value="普通大众">普通大众（轻松、易懂）</Radio>
                <Radio value="行业专家">行业专家（深度、专业）</Radio>
                <Radio value="学生群体">学生群体（通俗、教育性）</Radio>
              </Space>
            </Radio.Group>
          </Card>

          {/* 篇幅配置 */}
          <Card title="2. 设置文章篇幅" size="small">
            {/* 字数设置 */}
            <div style={{ marginBottom: 16 }}>
              <Text strong style={{ display: 'block', marginBottom: 8 }}>
                文章字数：
              </Text>

              {/* 快捷按钮 */}
              <Space size="small" style={{ marginBottom: 8 }}>
                {WORD_COUNT_PRESETS.map(preset => (
                  <Button
                    key={preset.value}
                    size="small"
                    type={totalWords === preset.value ? 'primary' : 'default'}
                    onClick={() => handlePresetClick(preset.value)}
                  >
                    {preset.label} ({preset.value}字)
                  </Button>
                ))}
              </Space>

              {/* 自定义输入 */}
              <div style={{ marginTop: 8 }}>
                <InputNumber
                  value={totalWords}
                  onChange={handleWordsChange}
                  min={100}
                  max={5000}
                  step={100}
                  addonAfter="字"
                  style={{ width: 180 }}
                />
                <Text type="secondary" style={{ marginLeft: 8, fontSize: 12 }}>
                  支持 100-5000 字
                </Text>
              </div>
            </div>

            <Divider style={{ margin: '12px 0' }} />

            {/* 段落数设置 */}
            <div>
              <Text strong style={{ display: 'block', marginBottom: 8 }}>
                段落数量：
              </Text>
              <Space align="center">
                <InputNumber
                  value={sectionCount}
                  onChange={handleSectionCountChange}
                  min={currentRule.minSections}
                  max={currentRule.maxSections}
                  addonAfter="段"
                  style={{ width: 140 }}
                />
                <Text type="secondary" style={{ fontSize: 12 }}>
                  推荐 {currentRule.recommendedSections} 段
                </Text>
                <Tooltip
                  title={`基于${totalWords}字的文章，建议${currentRule.minSections}-${currentRule.maxSections}段`}
                >
                  <QuestionCircleOutlined style={{ color: '#999' }} />
                </Tooltip>
              </Space>
            </div>

            {/* 配置预览 */}
            <Alert
              message={validation.text}
              type={validation.type}
              showIcon
              style={{ marginTop: 12 }}
            />
          </Card>
        </>
      )
    }

    if (dialogStep.options) {
      // 选择题形式
      return (
        <Card title="请选择您的答案" size="small">
          <Radio.Group
            value={selectedOption}
            onChange={(e) => setSelectedOption(e.target.value)}
            style={{ width: '100%' }}
          >
            <Space direction="vertical" style={{ width: '100%' }}>
              {dialogStep.options.map((option, index) => (
                <Radio key={index} value={option} style={{ fontSize: 14 }}>
                  {option}
                </Radio>
              ))}
            </Space>
          </Radio.Group>
        </Card>
      )
    } else {
      // 文本输入形式
      return (
        <Card title="请输入您的回答" size="small">
          <TextArea
            value={userInput}
            onChange={(e) => setUserInput(e.target.value)}
            onKeyDown={handleKeyDown}
            placeholder={dialogStep.placeholder || '请详细描述...'}
            autoSize={{ minRows: 3, maxRows: 6 }}
            maxLength={500}
            showCount
          />
          <div style={{ marginTop: 8, fontSize: 12, color: '#999' }}>
            提示：按 Ctrl+Enter 或 ⌘+Enter 快速提交
          </div>
        </Card>
      )
    }
  }

  // 检查是否可以提交
  const canSubmit = () => {
    if (dialogStep.type === DialogStepType.AUDIENCE_STYLE) {
      return selectedAudience.trim() !== ''
    } else if (dialogStep.options) {
      return selectedOption.trim() !== ''
    } else {
      return userInput.trim() !== ''
    }
  }

  // 判断是否在生成大纲
  const isGeneratingOutline = dialogState.currentStep === dialogState.totalSteps - 1 && isLoading

  // 如果正在生成大纲，显示加载界面
  if (isGeneratingOutline) {
    return (
      <div className="dialog-interface">
        {/* 进度步骤 */}
        {renderSteps()}

        {/* 已回答问题回顾 */}
        {renderPreviousAnswers()}

        {/* 大纲生成中的加载界面 */}
        <div style={{ textAlign: 'center', padding: '48px 24px' }}>
          <LoadingOutlined style={{ fontSize: 32, color: '#1890ff' }} />
          <div style={{ marginTop: 16, fontSize: 14, color: '#666' }}>
            正在生成文章大纲...
          </div>
        </div>
      </div>
    )
  }

  return (
    <div className="dialog-interface">
      {/* 进度步骤 */}
      {renderSteps()}

      {/* 已回答问题回顾 */}
      {renderPreviousAnswers()}

      {/* 当前问题 */}
      {renderQuestion()}

      {/* 回答区域 */}
      {renderResponseArea()}

      {/* 操作按钮 */}
      <div className="dialog-actions" style={{
        marginTop: 16,
        display: 'flex',
        justifyContent: 'space-between',
        alignItems: 'center'
      }}>
        <div>
          <Text style={{ fontSize: 12, color: '#666' }}>
            步骤 {dialogState.currentStep + 1} / {dialogState.totalSteps}
          </Text>
        </div>

        <Space>
          {dialogState.currentStep > 0 && (
            <Button
              icon={<ArrowLeftOutlined />}
              disabled={isLoading}
            >
              上一步
            </Button>
          )}

          <Button
            type="primary"
            icon={isLoading ? <LoadingOutlined /> : <ArrowRightOutlined />}
            onClick={handleSubmit}
            disabled={!canSubmit() || isLoading}
            loading={isLoading}
          >
            {dialogState.currentStep === dialogState.totalSteps - 1 ? '生成大纲' : '下一步'}
          </Button>
        </Space>
      </div>

      {/* 快捷操作提示 */}
      <div style={{
        marginTop: 12,
        padding: 8,
        background: '#f0f9ff',
        borderRadius: 4,
        fontSize: 12,
        color: '#666'
      }}>
        💡 您可以随时修改之前的回答，AI会根据最新信息为您定制文章大纲
      </div>
    </div>
  )
}

export default DialogInterface